Matrix product operators
Dense matrix product operators
There are 3 classes in this module: MPOSite, DenseMPO, DenseMPOList
DenseMPO
This is the standard textbook-like MPO that acts on specified sites (DenseMPO.sites).
It is a list of MPOSite-s
| | | |
-O-O-O-O-
| | | |
MPOSite
Each tensor in the DenseMPO is stored as MPOSite. For example,
a 4-body DenseMPO is going to be a list of 4 MPOSite-s.
|
-O-
|
DenseMPOList
A list of DenseMPO-s. Here, the DenseMPOList is usually
used to represent Hamiltonians. Hamiltonians are special because
they are normally a sum of polynomially-many tensor product operator (TPO) terms.
For local hamiltonians, each TPO acts on a finite number of sites.
Hence we can store a Hamiltonian as a list of TPO terms, where
each TPO is represented as a DenseMPO. For example,
the Ising model contains nearest-neighbour \(\sigma_x\sigma_x\) and
\(\sigma_z\) terms, and every 2-body TPO term \(\sigma_x\sigma_x\) and
local term \(\sigma_z\) would be stored as a separate DenseMPO
added to a DenseMPOList.
| | | | |
-O-O- , -O-O- , -O- , ...
| | | | |
Therefore, the number of sites in each individual DenseMPO in a
DenseMPOList does not correspond to the total number of sites - instead, it
corresponds to the number of sites on which the individual Hamiltonian
term is acting on.
Some useful attributes/functions
Initialize MPOSite with MPOSite([list of sites], tensor_str_name, pstrength=None, prefactor=1.0, operators=op_dict, params={})
MPOSite.site= on which site in a system does this MPO site actMPOSite.operator= get an actual tensorMPOSite.pstrength,MPOSite.weight= prefactors that multiply the elements of an operator.
The difference between pstrength and weight is that pstrength is parametrized via params dictionary
and weight is a number. The default prefactor is 1, i.e. pstrength=None and weight=1.
Initialize DenseMPO with DenseMPO([list of MPOSite-s], tensor_backend)
DenseMPO.num_sites= on how many sites does this MPO actDenseMPO.sites= list of sites on which MPO actsDenseMPO[ind].operator= get tensor on site indDenseMPO.append(MPOSite)= addMPOSitetoDenseMPO
Initialize DenseMPOList with DenseMPOList() and then append DenseMPO-s
DenseMPOList[ind]= getind-thDenseMPOin a listDenseMPOList.from_model_prepared(\*args, \*\*kwargs)= create aDenseMPOListobject from a given Hamiltonian model
See the more detailed documentation of individual functions below
- class qtealeaves.mpos.MPOSite(site, str_op, pstrength, weight, operators=None, params=None)[source]
One site in a dense MPO term. For example, a 4-body DenseMPO is going to be a list of 4 MPOSites.
- Initialize with MPOSite([list of sites], tensor_str_name, pstrength=None,
prefactor=1.0, operators=op_dict, params={})
Arguments
- siteinteger
Site index.
- str_opstr
Key for the operator.
- pstrengthpstrength, callable, numeric
Containing the parameterization of the term.
- weightscalar
Scalar constant prefactor.
- operators
TNOperatorsor None If present, operators will be directly extracted.
- paramsdict or None
If present, parameterization will be directly extracted.
- copy_with_new_op(operator)[source]
Create a copy of self, but with replacing the operator with the one passed. Corresponding string identifier will be set to None.
- classmethod from_operator(site, operator)[source]
Create MPOSite object from a given operator tensor.
Arguments
- siteint
Which site in a system.
- operator
_AbstractQteaBaseTensor’ Rank-4 tensor which will be the operator for this MPOSite.
Return
- mpo_site
MPOSite’ The resulting MPO site.
- property shape
Shape attribute equivalent to tensor’s shape: bond dimension of links.
- property total_scaling
Returns the scaling combining params and weight.
- class qtealeaves.mpos.DenseMPO(sites: Sequence[MPOSite] | None = None, convergence_parameters: TNConvergenceParameters | None = None, is_oqs: bool = False, tensor_backend: TensorBackend | None = None, require_singvals: bool = False, local_dim: int = 2)[source]
Dense MPO is the standard textbook-like MPO that acts on specified sites (DenseMPO.sites). It is a list of
MPOSite’s.Initialize with DenseMPO([list of MPOSite-s], tensor_backend)
- add_identity_on_site(idx, link_vertical)[source]
Add identity with the correct links to neighboring terms on site idx.
Parameters
- idxint
Site to which add the identity. Goes from 0 to num sites in a system.
- link_verticallink as returned by corresponding QteaTensor
Needed to build the local Hilbert space (in case it is different across the system).
- compress_links(idx_start, idx_end, trunc=False, conv_params=None)[source]
Compresses links between sites in a dense MPO by performing a QR or SVD, optionally performs the additional truncation along the way.
Parameters
- idx_startint
MPO site from which to start the compression.
- idx_endint
MPO site on which to end the compression.
- truncBoolean, optional
If True, the truncation will be done according to the conv_params. Default to False.
- conv_params
TNConvergenceParameters, optional Convergence parameters for the truncation. Must be specified if trunc is set to True. Default to None.
- classmethod from_density_matrix(rho, n_sites, dim, conv_params, tensor_backend=None, prob=False)[source]
Conversion of density matrix to DenseMPO (not implemented yet).
- classmethod from_lptn(lptn, conv_params=None, **kwargs)[source]
Conversion of LPTN to DenseMPO (not implemented yet).
- classmethod from_matrix(matrix, sites, dim, conv_params, tensor_backend=None, operators=None, pad_with_identities=False)[source]
For a given matrix returns dense MPO form decomposing with SVDs
Parameters
- matrixQteaTensor | ndarray
Matrix to write in (MPO) format
- sitesList[int]
Sites to which the MPO is applied
- dimint
Local Hilbert space dimension
- conv_params
TNConvergenceParameters Convergence parameters. The relevant attribute is the max_bond_dimension
- tensor_backendinstance of
TensorBackend Default for None is
QteaTensorwith np.complex128 on CPU.- operators: TNOperators, optional
Operator class. Default for None is empty TNOperator instance.
- pad_with_identities: bool, optional
If True, pad with identities the sites between min(sites) and max(sites) that have no operator. Default to False.
Return
- DenseMPO
The MPO decomposition of the matrix
- classmethod from_mps(mps, conv_params=None, **kwargs)[source]
Conversion of MPS to DenseMPO (not implemented yet).
- classmethod from_statevector(statevector, local_dim=2, conv_params=None, tensor_backend=None)[source]
No statevector for operators
- classmethod from_tensor_list(tensor_list, conv_params=None, iso_center=None, tensor_backend=None, operators=None, sites=None)[source]
Initialize the dense MPO from a list of tensors.
Parameters
- tensor_listList[QteaTensor] | List[MPOSite] | list[np.ndarray]
Matrix to write in (MPO) format. np.ndarray only allowed for systems without symmetry.
- conv_params
TNConvergenceParameters, None Input for handling convergence parameters. Default to None
- iso_centerNone, int, List[int], str, optional
If None, the center is None. If str, the iso center is installed If int, the iso center is that integer. Default is None
- tensor_backendinstance of
TensorBackend Default for None is
QteaTensorwith np.complex128 on CPU.- operators: TNOperators, optional
Operator class. Default for None is empty TNOperator instance.
- sitesList[int], None
Sites to which the MPO is applied. If None, they are assumed to be [0, 1, …, len(tensorlist)-1]. Default to None
Return
- DenseMPO
The MPO decomposition of the matrix
- classmethod from_ttn(ttn, conv_params=None, **kwargs)[source]
Conversion of TTN to DenseMPO (not implemented yet).
- classmethod from_tto(tto, conv_params=None, **kwargs)[source]
Conversion of TTO to DenseMPO (not implemented yet).
- static generate_mpo_identity(left_bd, local_dim, right_bd, tensor_backend)[source]
Generate an identity in MPO form with given dimensions.
- get_pos_partner_link_expansion(pos)[source]
Get the position of the partner tensor to use in the link expansion subroutine
Parameters
- posint | Tuple[int]
Position w.r.t. which you want to compute the partner
Returns
- int | Tuple[int]
Position of the partner
- int
Link of pos pointing towards the partner
- int
Link of the partner pointing towards pos
- initialize(operators, params)[source]
Resolve operators and parameterization for the given input for each site.
- ml_get_gradient_single_tensor(pos)[source]
Get the gradient w.r.t. to the tensor at
possimilar to the two-tensor version. Not implemented.
- ml_get_gradient_two_tensors(pos, pos_p=None)[source]
Get the gradient w.r.t. to the tensor at
possimilar to the two-tensor version. Not implemented.
- classmethod ml_initial_guess(convergence_parameters, tensor_backend, initialize, ml_data_mpo, dataset)[source]
Generate an initial guess for a tensor network machine learning approach.
Arguments
- convergence_parameters
TNConvergenceParameters Class for handling convergence parameters. In particular, the parameter ini_bond_dimension is of interest when aiming to tune the bond dimension of the initial guess.
- tensor_backend
TensorBackend Selecting the tensor backend to run the simulations with.
- initializestr
The string
superposition-datawill trigger the superposition of the data set. All other strings will be forwarded to the init method of the underlying ansatz.- ml_data_mpo
MLDataMPO MPO of the labeled data set to be learned including the labels.
- datasetList[
MPS] Data set represented as list of MPS states. Same order as in ml_data_mpo.
Returns
- ansatz
_AbstractTN Standard initialization of TN ansatz or Weighted superposition of the data set, wehere the weight is the label-value plus an offset of 0.1.
- convergence_parameters
- ml_two_tensor_step(pos, num_grad_steps=1)[source]
Do a gradient descent step via backpropagation with two tensors and the label link in the environment.
- ml_update_conjugate_gradient_two_tensors(pos, pos_p=None)[source]
Get the optimized “two_tensors” at position pos, pos_p through Conjugate gradient descent strategy following a procedure based upon https://arxiv.org/pdf/1605.05775.pdf for the data_sample given.
the name of the variables in the following is chosen upon Conj. Grad. Algor. in https://en.wikipedia.org/wiki/Conjugate_gradient_method.
Not Implemented.
- move_pos(pos, device=None, stream=False)[source]
Move just the tensor in position pos with the effective operators insisting on links of pos on another device. Other objects like effective projectors will be moved as well. Acts in place.
Note: the implementation of the tensor backend can fallback to synchronous moves only depending on its implementation.
Parameters
- posint | Tuple[int]
Integers identifying a tensor in a tensor network.
- devicestr, optional
Device where you want to send the QteaTensor. If None, no conversion. Default to None.
- streambool | stream | None, optional
If True, use a new stream for memory communication given by the data mover. If False, use synchronous communication with GPU. If not a boolean (and not None), we assume it is a stream object compatible with the backend. None is deprecated and equals to False. Default to False (Use null stream).
- classmethod mpi_bcast(state, comm, tensor_backend, root=0)[source]
Broadcast a whole tensor network.
Arguments
- state
DenseMPO(for MPI-rank root, otherwise None is acceptable) State to be broadcasted via MPI.
- commMPI communicator
Send state to this group of MPI processes.
- tensor_backend
TensorBackend Needed to identity data types and tensor classes on receiving MPI threads (plus checks on sending MPI thread).
- rootint, optional
MPI-rank of sending thread with the state. Default to 0.
- state
- property num_sites
Length of the Dense MPO
- pad_identities(num_sites, eye_ops)[source]
Pad identities on sites which are not in MPO yet respecting the symmetry.
- classmethod product_state_from_local_states(mat, padding=None, convergence_parameters=None, tensor_backend=None)[source]
Construct a product (separable) state in a suitable tensor network form, given the local states of each of the sites.
- classmethod read(filename, tensor_backend, cmplx=True, order='F')[source]
Read a MPO from a formatted file.
- property sites
Generate list of site indices.
- class qtealeaves.mpos.DenseMPOList(*args)[source]
A list of dense MPOs, i.e., for building iTPOs or other MPOs.
Initialize with DenseMPOList() and then append DenseMPO-s
Here, usually, it’s used to represent Hamiltonians which consist of multiple terms. In this case, each Hamiltonian term is represented as a DenseMPO. For example, Ising model contains nearest-neighbour sigma_x sigma_x and sigma_z terms, and every 2-body term sigma_x sigma_x and local term sigma_z would be stored as a separate DenseMPO added to a DenseMPOList
- classmethod from_model(model, params, tensor_backend: TensorBackend | None = None)[source]
Fill class with
QuantumModeland its parameters. Not ready for measurement before initializing with the operators. For full preparation use from_model_prepared().
- classmethod from_model_prepared(model, params, operators, tensor_backend: TensorBackend | None = None, sym=None, generators=None)[source]
Returns fully prepared dense MPOs from a model, ready for the measurement. (Pay attention: this classmethod has two return values.)
Arguments
- model
QuantumModel The model to build the
DenseMPOListfor.- paramsdict
Simulation dictionary containing parameterization and similar settings for the model and simulation.
- operators
TNOperators The operators to be used with the simulation.
- tensor_backend
TensorBackend, optional Choose the tensor backend to be used for the operators and simulation. Default to TensorBackend() (numpy, CPU, complex128, etc.)
- symlist, optional
Information on symmetry in case of symmetric tensors. Default to None (no symmetries).
- generatorslist, optional
Information on the generators of the symmetry in case of symmetric tensors. Default to None (no symmetries).
Returns
- obj
DenseMPOListt MPO representation of the model for the given parameterization.
- operators
TNOperators Operators converted to the corresponding tensor backend.
- model
- property has_oqs
Return flag if the DenseMPOList contains any open system term.
- initialize(operators, params, do_sort=True)[source]
Resolve operators and parameterization for the given input.
- mpo_product(other, operators, self_conj=False, self_transpose=False, other_conj=False, other_transpose=False)[source]
Compute the product of two MPOs encoded as DenseMPOList. The order of product is self*other. If the operators at site j are self_op_j and other_op_j respectively, mpo_product returns the DenseMPOList whose operator at site j is the operator product self_op_j*other_op_j. The input arguments self and other remain unchanged in this method.
Parameters
- other
DenseMPOList Representing the operator that we are multiplying to self.
- operators
TNOperators The operator dictionary for the simulation. The corresponding second order operators are generated within the function if not set yet.
- self_conjBoolean, optional
Tells if self needs to be complex conjugated. Default is False.
- self_transposeBoolean, optional
Tells if self needs to be transposed. Default is False.
- other_conjBoolean, optional
Tells if other needs to be complex conjugated. Default is False.
- other_transposeBoolean, optional
Tells if other needs to be transposed. Default is False.
Return
- mpo_product
DenseMPOList The product of the operators represented by self and other.
Details
This function is potentially costly in terms of memory and computation time. While the computational complexity of this approach cannot be mitigated within DenseMPOLists, the memory requirements can be tuned by using _mpo_product_iter, which is an iterator over smaller DenseMPOLists.
- other
Indexed tensor product operators
This is the default MPO representation for the Hamiltonians and the observables which the library uses during computationally extensive operations in simulations. (The other option are sparse MPOs, but indexed tensor product operators (iTPOs) for now allow more generality.) Here is the short introduction to iTPO framework.
A Hamiltonian MPO (or any MPO operator) is often a sum of tensor product terms (TPOs), where every TPO term contains n operators acting on n sites. Therefore, as it is the case with dense MPOs (see above), we can treat the Hamiltonian as a list of TPO terms.
Very often, however, we have only few different operator tensors building the Hamiltonian:
the Ising Hamiltonian is, for example, built only from \(\sigma_x\) and
\(\sigma_z\) operators. Therefore, to save memory, we don’t have to define our
Hamiltonian MPO by saving every operator at every site (as it is done in a DenseMPOList),
but instead we can assign every operator tensor an index ii and store only the information
of type: “operator ii acting on site x with the prefactor w”, where ii points
to e.g. \(\sigma_x\) tensor. Every TPO term is assigned a unique integer TPO ID going
from 0 to number of TPO terms. The same TPO IDs are assigned to the corresponding operators
inside TPO terms, so we can keep track which operator belongs to which TPO term.
This way of representing MPOs is what we call the indexed TPO picture.
Another difference between iTPOs with respect to DenseMPO / DenseMPOLists is that local
terms are treated differently in the iTPO picture. All the local terms
acting on the same site are contracted into a single local term of same dimensions.
There are 3 classes in this module: ITPOTerm, ITPOSites, ITPO
ITPOTerm
ITPOTerm contains all operators acting on a single site, each coming
from a different TPO term in the MPO. The “Term” in the name is a bit misleading,
as ITPOTerm does not refer to the TPO term (which usually acts on more than one site),
but instead refers to a collection of operators acting on a single site.
ITPOTerm can contain one local term, which is treated separately and is stored
under ITPOTerm._local.
ITPO
The full MPO, containing all its TPO terms. In general, it has two parts: ITPO.site_terms
and ITPO.eff_ops. ITPO.site_terms are an instance of ITPOSites (description below)
and they represent the TPO terms coming from a Hamiltonian or any operator acting on the
physical sites of the tensor network. ITPO.eff_ops, on the other hand, represent all the TPO
terms inside the effective operators around each tensor in a tensor network. Therefore,
ITPO.eff_ops depend on a TN ansatz. In a simulation, ITPO.site_terms are usually the input
Hamiltonian and ITPO.eff_ops are computed by contracting this Hamiltonian with tensors in a TN.
ITPOSites
Represent the TPO terms coming from a Hamiltonian or any operator acting on physical sites of the
tensor network. Stored as a list of ITPOTerm-s, such that there is one ITPOTerm per
system site.
Some useful attributes/functions/remarks
ITPOTerm acts on a single site, but there is no attribute inside of it which tell
which site it is. This info is instead stored in ITPO and ITPOSites.
ITPOTerm._tensors: following the iTPO convention, this is a dictionary with all the tensors, where the key is the operator string which defines it and the value is a corresponding tensorITPOTerm._operators: a dictionary, with the key being a TPO ID of the corresponding TPO term in the parent ITPO and the value is the corresponding operator stringITPOTerm.weights: list of prefactors for every operator tensor inITPOTerm, ordered by TPO IDsITPOTerm._local: tensor of a local term, if any
The easiest way to create an ITPO is to first create a DenseMPOList, initialize
the empty ITPO with itpo = ITPO(num_sites), and then convert DenseMPOList to ITPO with
itpo.add_dense_mpo_list(DenseMPOList)
ITPO.site_terms:ITPOSites, i.e. a list ofITPOTerm-s that act on physical sites in a TNITPO.eff_ops: a dictionary of effective operators around every tensor in a tensor network. The keys in a dictionary specify which tensor we are looking at, with the convention differing for different TNs (e.g. for MPS, it’s just the index of the tensor, for TTN it’s(layer_idx, tensor_idx)). The value for each iterm inITPO.eff_opsis again a dictionary containing threeITPOTerm-s, as there are three effective operators per tensor. The convention for keys of this dictionary again differs for different TNs, but (roughly speaking) it’s supposed to specify whether the correspondingITPOTermis left, down, or right effective operator. Upon initialization,ITPO.eff_opsis an empty dictionary. The actual effective operators are computed onceITPO.contr_to_eff_op()is called.
See the more detailed documentation of individual functions below
- class qtealeaves.mpos.ITPOTerm(do_indexing=True, enable_update=False)[source]
Single iTPO term either for Hamiltonian or inside effective operators.
ITPOTerm contains all operators acting on a single site, each coming from a different TPO term in the MPO.
The “Term” in the name is a bit misleading, as it does not refer to the TPO term which usually acts on more than one site, but it refers to a collection of operators acting on a single site. Additionally, ITPOTerm can contain one local term that is treated separately and is stored under ITPOTerm._local.
- add_local(operator, prefactor, strength, pstrength, is_oqs)[source]
Add a local term to the iTPOTerm when building a Hamiltonian.
- add_term(tpo_id, operator, link_inds, prefactor, strength, pstrength, is_oqs)[source]
Add an interaction term to the iTPOTerm when building a Hamiltonian.
- convert(dtype, device, stream=None)[source]
Convert underlying array to the specified data type inplace.
- delete_or_cache_tensors(inds)[source]
Delete or cache entries (used to remove terms which contracted to local.
- property device
Device where the tensor is stored.
- property dtype
Data type of the underlying arrays.
- empty_copy(other=None, do_copy_meas_vec=False)[source]
Make a copy of the settings of a term without entries.
- property enable_update
Property if update of time-dependent couplings is enabled.
- filter_tpo_ids(filter_tpo_ids)[source]
Removes all operators that do not have a tpo-id given by filter_tpo_ids.
Parameters
- filter_tpo_idslist[ int ]
Tpo-ids that are not removed.
Returns
- filtered_opITPOTerm
The operator with filtered ITPO-ids.
- static get_case_funcs()[source]
Construct the mapping between contraction cases as integers and their functions.
Details
The cases and their IDs are a one-to-one copy from the fortran code. At the beginning, we had even more of them with every possible combination of contracting rank-3 and rank-4 MPOs with 0, 1, and 2 matching horizontal links. Now, they contain only rank-4 MPOs with 1 and matching horizontal links plus the local term rules at -10, -20. To simplify coding, the cases have each their own function (where in fortran it was still a select case).
Copy-pasted from each-functions docstring:
1) only left has TPO-ID 7) lr and rl match to local term 8) ll and rr match to local term 34) match rl and keeping as TPO-ID 43) match lr and keeping as TPO-ID 53) match ll and keeping as TPO-ID 63) match rr and keeping as TPO-ID 99) only right has TPO-ID -10) local term in left -20) local term in right
- property has_oqs
Return flag if the iTPOTerm contains any open system term.
- property idx_eye
By convention, we will set the “eye” tensor at key -2.
- property local_dim
Return the local dimension of the ITPOTerm as int.
- matrix_multiply(other, cidx_self, cidx_other, eye_a=None, eye_b=None, perm_local_out=None, ctens=None)[source]
Contract of two iTPOTerms.
Arguments
- otherinstance of
iTPOTerm Right / second term in the multiplication
- cidx_selflist of ints
Contraction legs for full TPO tensor (local will auto-adapt)
- cidx_otherlist of ints
Contraction legs for full TPO tensor (local will auto-adapt)
- eye_ainstance of
_AbstractQteaTensoror None, optional If self is not a rank-4 iTPOTerm, pass what should be used as identity. Default to None
- eye_binstance of
_AbstractQteaTensoror None, optional If other is not a rank-4 iTPOTerm, pass what should be used as identity. Default to None
- perm_local_outlist of ints or None, optional
Permutation of output (full TPO tensor will auto-adapt) (MPO links will be permuted in first and last place automatically) Default to None
- ctensNone or
ITPOTerm If present, update mode is activating which assumes that only a scalar weight has changed.
- otherinstance of
- run_measurements(ket, idx_out, link_weights)[source]
Run the measurements on the iTPOTerm, i.e., on all stored local tensors.
- stream(disable_streams=False)[source]
Define a stream for any operation
Parameters
- disable_streamsbool, optional
Allows to disable streams to avoid nested creation of streams. Globally, streams should be disabled via the set_streams_qteatensors function of the base tensor module. Default to False.
Returns
Context manager, e.g.,
to.cuda.Streamif on GPUnullcontext(AbstractContextManager)otherwise
- tensordot_with_tensor(tensor, cidx_self, cidx_tensor, perm_local_out=None, ctens=None)[source]
Execute contraction of iTPOTerm with tensors. Uncontracted non-MPO (non-horizontal) legs of self go before uncontracted non-MPO legs of tensor.
Arguments
- tensorinstance of
_AbstractQteaTensor Tensor in the contraction as right/second tensor.
- cidx_selflist of ints
Contraction legs for full TPO tensor (local will auto-adapt)
- cidx_tensorlist of ints
Contraction legs for the tensor
- perm_local_outlist of ints
Permutation of output (full TPO tensor will auto-adapt)
- ctensNone or
ITPOTerm If present, update mode is activated which assumes that only a scalar weight has changed.
Returns
- ctens
ITPOTerm Result of contraction.
- tensorinstance of
- tensordot_with_tensor_left(tensor, cidx_tensor, cidx_self, perm_local_out=None, ctens=None)[source]
Execute contraction of iTPOTerm with tensor. Uncontracted non-MPO (non-horizontal) legs of tensor go before uncontracted non-MPO legs of self.
Arguments
- tensorinstance of
_AbstractQteaTensor Tensor in the contraction as right/second tensor.
- cidx_tensorlist of ints
Contraction legs for the tensor
- cidx_selflist of ints
Contraction legs for full TPO tensor (local will auto-adapt)
- perm_local_outlist of intes
Permutation of output (full TPO tensor will auto-adapt)
- ctensNone or
ITPOTerm If present, update mode is activating which assumes that only a scalar weight has changed.
Returns
- ctens
ITPOTerm Result of contraction.
- tensorinstance of
- class qtealeaves.mpos.ITPOSites(num_sites, do_indexing, enable_update)[source]
ITPOSites contains the physical terms = list ITPOTerms in the Hamiltonian or any operator acting on physical sites of a TN. There’s one ITPOTerm per system site.
- add_dense_mpo_list(dense_mpo_list)[source]
Add terms from a
DenseMPOListto the iTPO sites.
- construct_tensor_backend()[source]
Construct the tensor backend. Finds a tensor_like, which is either a local_ops tensor or a tensor from the first interaction term, and parses its tensor_backend.
- property has_oqs
Flag if MPO has Lindblad terms (just present, not looking at coupling).
- to_dense_mpo_list_unparameterized(op_dict, prefix_op_key='')[source]
Convert site terms into dense MPO list while loosing access to the parameterization. If you need to maintain parameterization, use to_dense_mpo_list.
Arguments
- op_dict
TNOperators Dictionary with the operators, can be modified inplace to add more operators.
- prefix_op_keystr, optional
Prefix to the operators key to avoid duplicates with different representation of the operator. Default to “” (empty string, no prefix)
Returns
- mpo
DenseMPOList MPO represented as DenseMPOList instead of an ITPO. Parameterization cannot be updated, i.e., weights are fixed now.
- op_dict
- class qtealeaves.mpos.ITPO(num_sites, do_compress=False, do_indexing=True, enable_update=False)[source]
iTPO with Hamiltonian and effective operators, e.g., for ground state search. Consists of the full Hamiltonian (ITPO.site_terms) + effective operators for every site and position (ITPO.eff_ops).
ITPO.site_terms are a class of ITPOSites and they represent the TPO terms coming from a Hamiltonian or any operator acting on the physical sites of the tensor network.
ITPO.eff_ops depend on a TN ansatz. In a simulation, ITPO.site_terms are usually the input Hamiltonain, and ITPO.eff_ops are computed by contracting this Hamiltonian with tensors in a TN.
Arguments
- num_sitesint
Number of sites in the system, e.g., qubits.
- do_compressbool, optional
Flag if compression should be activated (True). Default
False(no compression).- do_indexingbool, optional
Flag if indexing should be used (True) or if running as TPO (False). Default to
True- enable_updatebool, optional
Flag if smart update of time-dependent parameters should be activated (True). Activation also caches additional states on top of the effective operators. Default to False (no smart update).
Details
The indexed tensor product operator comes in different flavors:
TPO : without indexing, pass do_indexing flag.
iTPO : with indexing, only unique operators are contracted (default)
iuTPO : iTPO with smart update for time-evolution: pass flag enable_update on initialization, moreover do_update has to be set and unset when updating the coupling of the Hamiltonian.
icTPO : iTPO with compression, set flag do_compress, which is beneficial for systems with many interactions.
iucTPO : iTPO with compression and smart update for time-dependent parameters.
- add_dense_mpo_list(dense_mpo_list)[source]
Add terms from a
DenseMPOListto the iTPO sites.
- collect_measurements(num_terms=None)[source]
Collect the measurements from measurement setup of iTPO.
- compress(pos_tuple)[source]
Compress iTPOTerm at a given position.
Arguments
- pos_tupletuple
position of the effective operator to be compressed via two tensor positions
Details
Considering an eight-site MPS-like structure with all-to-all two-body interactions the terms by default at link between sites 6 and 7 are
1 acting at 7 and 8
2 acting at 7 and 8
3 acting at 7 and 8
4 acting at 7 and 8
5 acting at 7 and 8
6 acting at 7 and 8
and will be compressed to
(1 + 2 + 3 + 4 + 5 + 6) acting at 7
(1 + 2 + 3 + 4 + 5 + 6) acting at 8
Thus, compression makes potentially sense for many interactions and if more than half of the system is integrated into an effective operator. The latter is checked to avoid unnecessary execution.
- contr_to_eff_op(tensor, pos, pos_links, idx_out)[source]
Contract operator lists with tensors T and Tdagger to effective operator.
Arguments
- tensor
_AbstractQteaTensor Tensor to be contracted to effective operator.
- posint, tuple (depending on TN)
Position of tensor.
- pos_linkslist of int, tuple (depending on TN)
Position of neighboring tensors where the links in tensor lead to.
- idx_outint
Uncontracted link to be used for effective operator.
- tensor
- contract_tensor_lists(tensor, pos, pos_links, custom_ops=None, pre_return_hook=None)[source]
Linear operator to contract all the effective operators around the tensor in position pos. Used as a matrix-vector multiplication function in solvers.
Arguments
- tensor
_AbstractQteaTensor Tensor to be contracted to effective operator.
- posint, tuple (depending on TN)
Position of tensor.
- pos_linkslist of int, tuple (depending on TN)
Position of neighboring tensors where the links in tensor lead to.
- custom_opsNone or list of
ITPOTerm Ordered list of iTPO terms for tensor, which should be used instead of information in pos and pos_links.
- pre_return_hook??
???
Return
- ctens
_AbstractQteaTensor The tensor contracted with effective operators.
- tensor
- convert(dtype, device)[source]
Convert underlying array to the specified data type inplace. Original site terms data type is preserved, while the device is converted.
- property device
Device where the tensor is stored.
- property do_update
Status of the flag for doing update of effective operators.
- property dtype
Data type of the underlying arrays.
- get_ctens_for_update(key, identifier)[source]
Extract a tensor for update of time-dependent coupling from cache.
Arguments
- keyimmutable
Key from effective operator to be built serving as base key.
- identifier :
Extension to identity step when building effective operator.
Returns
- ctensinstance of
ITPOTermor None Retrieve tensor from cache if updates are enabled.
- ukeystr or None
Key for storing tensor again.
- get_local_kraus_operators(dt)[source]
Constructs local Kraus operators from local Lindblad operators.
Parameters
dt : float, timestep
Returns
- kraus_opsdict of
QTeaTensor Dictionary, keys are site indices and elements the corresponding 3-leg kraus tensors
- kraus_opsdict of
- property has_oqs
Flag if MPO has Lindblad terms (just present, not looking at coupling).
- mpo_product(other, self_conj=False, self_transpose=False, other_conj=False, other_transpose=False)[source]
Compute the product of two ITPOs. The order of the product is self*other.
Parameters
- other
ITPO Representing the operator that we are multiplying to self. other is the right-hand-side operator in the multiplication.
- self_conjBoolean, optional
Tells if self needs to be complex conjugated. Default is False.
- self_transposeBoolean, optional
Tells if self needs to be transposed. Default is False.
- other_conjBoolean, optional
Tells if other needs to be complex conjugated. Default is False.
- other_transposeBoolean, optional
Tells if other needs to be transposed. Default is False.
Returns
- mpo_product
ITPO Representing the products of the operators represented by self and other.
Details
This function is potentially costly in terms of memory and computation time. The ITPO obtained from this function cannot be changed by parameterization.
- other
- property num_sites
Return the number of sites in the underlying system.
- set_ctens_for_update(ukey, ctens)[source]
Set a tensor for time-dependent coupling updates (if enabled).
- set_meas_status(do_measurement=True)[source]
Set the measurement status for all iTPOTerms in iTPOSites.
- setup_as_eff_ops(tensor_network, measurement_mode=False)[source]
Set this sparse MPO as effective ops in TN and initialize.
- to_dense_mpo_list(params, do_initialize=True)[source]
Return the dense MPO form of the site terms, requires params dict.
Sparse matrix operators
- class qtealeaves.mpos.SparseMatrixOperator(is_first, is_last, do_vecs)[source]
A single indexed sparse MPO representing one site.
Arguments
- is_firstbool
Flag if sparse matrix operator represents first site.
- is_lastbool
Flag if sparse matrix operator represents last site.
- do_vecsbool
For periodic boundary conditions aiming at actual matrices for all sites, set to False. For True, the first and last site will use vectors.
- class qtealeaves.mpos.SparseMatrixOperatorPy(is_first, is_last, do_vecs, operator_eye, tensor_backend=None)[source]
Sparse MPO matrix for one site and the python implementation.
- add_term(sp_mat, pstrength, prefactor, weight, mapping)[source]
Adding a non-local terms via its SPO matrix.
Arguments
sp_mat : np.ndarray
pstrength : parameterized couplings via integer ID appearing again in mapping
prefactor : scalar constant coupling
weight : combining pstrength and prefactor with initial values
- mappingdict, mapping integers from pstrength into parameterized values
(where values can be strings, scalars, callables).
- collapse(params)[source]
Collapse function recalculates local and interaction terms based on the new couplings passed via params dictionary.
- collapse_interactions(params)[source]
Collapse function recalculates interaction terms based on the new couplings passed via params dictionary.
- property device
Device where the tensor is stored.
- property dtype
Data type of the underlying arrays.
- matrix_multiply(other, cidx_self, cidx_other, perm_out=None)[source]
Contract two sparse MPOs (rows/cols contracted automatically, permutation has to be on full).
- property ndim
Rank of the underlying tensor extracted from the first element.
- tensordot_with_tensor(tensor, cidx_self, cidx_tensor, perm_out=None)[source]
Execute contraction of sparseMPO with tensors.
- tensordot_with_tensor_left(tensor, cidx_tensor, cidx_self, perm_out=None)[source]
Execute contraction of tensor with sparse MPO (tensor first arg in tensordot).
- to_dense_mpo_matrix(diag_only=False)[source]
Convert the sparse MPO into a dense matrix.
The weights are considered during the conversion, but any parameterization is lost. Sparse MPOs with symmetric tensors cannot be converted.
- Args:
- diag_onlyflag if only the diagonal terms should be
extracted (True) or the whole matrix (False). Sometimes the digaonal is sufficient for debugging purposes. Default to False.
- Returns:
dense_mat (_AbstractQteaTensor) : the dense matrix representing the sparse MPO matrix compatible with the backend.
Sparse matrix product operators
- class qtealeaves.mpos.SparseMPO(num_sites, operators, do_vecs=True, tensor_backend=None)[source]
Representation of a sparseMPO for python.
- add_dense_mpo_list(dense_mpo_list, params, indexed_spo=True)[source]
Add terms for
DenseMPOListto the SparseMPO.
- contr_to_eff_op(tensor, pos, pos_links, idx_out)[source]
Contract operator lists with tensors T and Tdagger to effective operator.
- contract_tensor_lists(tensor, pos, pos_links, custom_ops=None, pre_return_hook=None)[source]
Linear operator to contract all the effective operators around the tensor in position pos. Used in the optimization.
- convert(dtype, device)[source]
Convert underlying array to the speificed data type inplace. Original site terms are preserved.
- property device
Device where the tensor is stored.
- property dtype
Data type of the underlying arrays.
- property num_sites
Return the number of sites in the underlying system.
- class qtealeaves.mpos.SparseMatrixProductOperator(params, model, operator_map, param_map)[source]
Indexed sparse MPO for a set of sites.
Arguments
- paramsdict
Parameterization of a simulation.
- modelinstance of QuantumModel
The physical model to be converted into an MPO.
- operator_mapdict
Mapping the operators to their integer IDs.
- param_mapdict
Mapping the parameters to their integer IDs.
Abstract effective operators
- class qtealeaves.mpos._AbstractEffectiveOperators[source]
Any effective operator or overlap.
Details
Effective operators should implement at least a dictionary functionality where the keys are made of a tuple of two entries, where each entry is the position of a tensor in the tensor network. The key (pos_a, pos_b) provides the effective operators of the tensor at pos_a contracted except for the link leading to the tensor at pos_b. The position itself can be implemented depending on the needs of the tensor networks, e.g., as integer or tuple of integers. Only each link needs a unique pair of positions.
- abstractmethod contr_to_eff_op(tensor, pos, pos_links, idx_out)[source]
Calculate the effective operator along a link.
- abstractmethod contract_tensor_lists(tensor, pos, pos_links, custom_ops=None, pre_return_hook=None)[source]
Linear operator to contract all the effective operators around the tensor in position pos. Used in the optimization.
- abstractmethod convert(dtype, device)[source]
Convert underlying array to the specified data type inplace. Original site terms are preserved.
- abstract property device
Device where the tensor is stored.
- abstract property dtype
Data type of the underlying arrays.
- property has_oqs
Return if effective operators is open system (if no support, always False).
- abstract property num_sites
Return the number of sites in the underlying system.
Disentanglers
- class qtealeaves.mpos.DELayer(num_sites, de_sites, convergence_parameters, local_dim=2, tensor_backend=None, initialize='identity', check_unitarity=True)[source]
Disentangler layer, i.e. the list of disentangler tensors. All the DE tensors must be unitary. One can access a specific tensor by checking DELayer[ind]. In aTTN, DELayer can be accessed via ATTN.de_layer. The leg ordering in disentangler is:
^ ^ | | 0 1
<psi|
Parameters
- num_sitesint
Number of sites
- de_sites2d np.array, optional
Array with disentangler positions with n rows and 2 columns, where n is the number of disentanglers. Counting starts from 0 and indices are passed as in the mapped 1d system. If set to ‘auto’, the disentangler positions are automatically selected to fit as much disentanglers as possible. Default to ‘random’.
- convergence_parameters:
TNConvergenceParameters Class for handling convergence parameters. In particular, in the aTTN simulator we are interested in: - the maximum bond dimension \(\chi\); - the cut ratio \(\epsilon\) after which the singular
values are neglected, i.e. if \(\lambda_1\) is the bigger singular values then after an SVD we neglect all the singular values such that \(\frac{\lambda_i}{\lambda_1}\leq\epsilon\)
- local_dim: int, optional
Local Hilbert space dimension. Default to 2.
- tensor_backendNone or instance of
TensorBackend, optional Default for None is
QteaTensorwith np.complex128 on CPU.- initializestring, optional
Define the initialization method. For identities use ‘identity’, for random entries use ‘random’. Default to ‘identity’.
- check_unitarityBoolean, optional
If True, all the disentangler tensors are checked for unitarity and an error is raised if the check fails. Default to True.
- apply_de_to_dense_mpo(de_ind, dense_mpo, tensor_backend)[source]
Contracts DE and DE^dag with a given dense MPO. Since there could be the sites which are in mpo, but not in DE (and vice versa), the function takes care to insert identity operators on appropriate places.
Parameters
- de_indint
Index of disentangler which we want to contract with mpo.
- dense_mpoDenseMPO
Dense MPO to be contracted with disentangler.
- tensor_backend: TensorBackend
Tensor backend of the simulation.
Return
- contracted_dense_mpoDenseMPO
Dense MPO contracted with disentangler.
Don’t forget the truncation. Raise a warning if truncating.
- check_if_de_eligible(tensor)[source]
Makes several checks and raises an exception if a tensor is not eligible for a disentangler.
- property check_unitarity
Flag to check if disentanglers are unitaries.
- class_allowed
alias of
_AbstractQteaTensor
- contract_de_layer(itpo, tensor_backend, params)[source]
Contracts the disentangler layer with a given iTPO. The procedure contracts the itpo between DE layer and DE^dag layer as a sandwich:
- (DE layer)
- (iTPO)
(DE^dag layer)
Parameters
- itpoITPO
iTPO which is to be contracted with the DE layer
- tensor_backend: TensorBackend
Tensor backend of the simulation.
- paramsdict or None, optional
The parameters passed from the simulation. Needed to transfrom the itpo to a DenseMPOList.
Return
- contracted_itpoITPO
iTPO resulting from contracting itpo with DE layer.
- property convergence_parameters
Get the convergence settings.
- generate_identity_disentangler(link1, link2, tensor_backend)[source]
Generate an identity disentangler which connects the two sites. ** Arguments ** link1, link2 : int | link
Links corresponding to the two sites of the disentnangler.
- tensor_backendTensorBackend
The TensorBackend for the disentangler tensor.
- property local_dim
Local dimension property
- property num_de
Number of disentanglers.
- property num_sites
Number of sites property
- to_dense_mpo(de_ind, tensor_backend)[source]
Splits the chosen disentangler into left and right operator and stores them as a dense MPO.
Parameters
- de_indint
Index of disentangler which we want to store as dense MPO.
- tensor_backend: TensorBackend
Tensor backend of the simulation.
Return
- dense_deDenseMPO
Dense MPO with left and right disentangler as terms.